package com.ccrego.haiyi.utils;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Environment;

import java.io.File;

/**
 * Created by yafenchen on 2017/4/9.
 */

public class CacheManager {
    private long totalsize = 0l;

    public long getTotalsize() {
        return totalsize;
    }

    public long getTotalCacheSize(Context context) throws Exception {
        long cacheSize = getFolderSize(context.getCacheDir());
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            cacheSize += getFolderSize(context.getExternalCacheDir());
        }
        totalsize = cacheSize;
        return cacheSize;
    }

    //清理缓存
    public void clearAllCache(Context context) {
        if (totalsize == 0) {
            try {
                getTotalCacheSize(context);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (totalsize >= 0) {
            deleteDir(context.getCacheDir());
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                deleteDir(context.getExternalCacheDir());
            }
        }
        totalsize = 0l;
    }

    private static boolean deleteDir(File dir) {
        if (dir != null && dir.isDirectory()) {
            String[] children = dir.list();
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        return dir.delete();
    }

    // 获取文件
    //Context.getExternalFilesDir() --> SDCard/Android/data/你的应用的包名/files/ 目录，一般放一些长时间保存的数据
    //Context.getExternalCacheDir() --> SDCard/Android/data/你的应用包名/cache/目录，一般存放临时缓存数据
    public static long getFolderSize(File file) throws Exception {
        long size = 0;
        try {
            File[] fileList = file.listFiles();
            for (int i = 0; i < fileList.length; i++) {
                // 如果下面还有文件
                if (fileList[i].isDirectory()) {
                    size = size + getFolderSize(fileList[i]);
                } else {
                    size = size + fileList[i].length();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return size;
    }

    /**
     * 格式化单位
     * 最小的数值为0.1M，只计算到小数点后1位  ， KB与B不统计
     * 达到1024M既算为1G， 达到1024KB既算1M
     *
     * @param size
     * @return
     */
    public static String getFormatSize(long size) {
        final long MB = 1024 * 1024;
        final String M = " M";
        final String G = " G";
        //小于0.1M
        if (size - MB * 0.1 < 0.0) {
            return "0.1" + M;
        }

        float divide = size / (MB * 1.0f);   //单位M
        //达到1024M
        if (divide - 1024.0 >= 0.0) {
            divide /= 1024;   //换算为G
            return String.format("%.1f%s", divide, G);
        } else {
            return String.format("%.1f%s", divide, M);
        }
    }

    /**
     * 缓存大小统计结果回调
     */
    public interface StatCacheSizeCallback {
        void onStatCompleted(long sizeString);
    }

    public interface ClearCacheCallback {
        void onClearCompleted();
    }

    /**
     * 统计缓存大小, 异步方法. 结果返回后执行回调接口
     *
     * @param context  上下文
     * @param callback 缓存大小统计结果回调
     */
    public void statCacheSize(Context context, StatCacheSizeCallback callback) {
        new GetCacheInfoTask(context, callback).execute();
    }

    /**
     * 清除所有缓存文件, 异步方法. 结果返回后执行回调接口
     *
     * @param context  上下文
     * @param callback 缓存大小统计结果回调
     */
    public void clearCache(Context context, ClearCacheCallback callback) {
        new ClearCacheTask(context, callback).execute();
    }

    /**
     * 发出统计缓存大小的广播任务,
     * 返回后设置textView 显示占用大小文本
     */
    class GetCacheInfoTask extends AsyncTask<Object, Object, Long> {

        private Context context;
        private StatCacheSizeCallback callback;

        public GetCacheInfoTask(Context context, StatCacheSizeCallback callback) {
            this.context = context;
            this.callback = callback;
        }

        @Override
        protected Long doInBackground(Object... params) {
            long totalsize = 0l;
            try {
                totalsize = getTotalCacheSize(context);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return totalsize;
        }

        @Override
        protected void onPostExecute(Long sizStr) {
            if (callback != null) {
                callback.onStatCompleted(sizStr);
            }
        }
    }

    /**
     * 清空缓存任务
     */
    class ClearCacheTask extends AsyncTask<Object, Object, Boolean> {

        private Context context;
        private ClearCacheCallback callback;

        private ProgressDialog progressDialog;

        public ClearCacheTask(Context context, ClearCacheCallback callback) {
            this.context = context;
            this.callback = callback;
        }

        @Override
        protected void onPreExecute() {
            if (totalsize <= 0) {
                this.cancel(true);
            } else {
                progressDialog = ProgressDialog.show(context, "",
                        "清除缓存中", true);
            }
        }

        @Override
        protected Boolean doInBackground(Object... params) {
            clearAllCache(context);
            return true;
        }

        @Override
        protected void onPostExecute(Boolean aBoolean) {
            if (progressDialog.isShowing()) {
                progressDialog.dismiss();
            }

            if (callback != null) {
                callback.onClearCompleted();
            }
        }
    }
}
